package com.ruoyi.project.monitor.syslog;

import com.ruoyi.project.monitor.entity.SysLoginLog;
import com.ruoyi.project.monitor.entity.SysOperLog;
import com.ruoyi.project.monitor.service.ISysLoginLogService;
import com.ruoyi.project.monitor.service.ISysOperLogService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.common.error.MicaErrorEvent;
import net.dreamlu.mica.launch.MicaProperties;
import net.dreamlu.mica.server.ServerInfo;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;

/**
 * Event 监听
 *
 * @author dy
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@AllArgsConstructor
public class SysLogListener {
    private final ISysLoginLogService sysLoginLogService;

    private final ISysOperLogService sysOperLogService;

    private final MicaProperties micaProperties;

    private final ServerInfo serverInfo;

    /**
     * 监听登陆
     */
    @Async
    @EventListener(SysLoginLog.class)
    public void saveSysLoginLog(SysLoginLog sysLoginLog) {
        sysLoginLogService.save(sysLoginLog);
    }

    /**
     * 监听操作
     */
    @Async
    @EventListener(SysOperLog.class)
    public void saveSysOperLog(SysOperLog sysOperLog) {
        sysOperLogService.save(sysOperLog);
    }

    /**
     * 监听错误
     */
    @Async
    @EventListener(MicaErrorEvent.class)
    public void saveErrorLog(MicaErrorEvent event) {

        event.setAppName(micaProperties.getName());
        event.setEnv(micaProperties.getEnv());
        event.setRemoteHost(serverInfo.getHostName());

        SysOperLog sysOperLog = SysLogUtils.me().turnErrorToOper(event);
        if (sysOperLog != null) {
            sysOperLogService.save(sysOperLog);
        }
    }
}
